package com.stfalcon.chatkit.sample.listenser;

import android.content.Context;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.stfalcon.chatkit.sample.common.data.ReceiveListData;
import com.stfalcon.chatkit.sample.common.data.model.User;
import com.stfalcon.chatkit.sample.task.AsyncRquest;
import com.stfalcon.chatkit.sample.url.URLConstant;

import org.json.JSONObject;

import java.util.List;

public class UserSearchListener implements TextWatcher {

    private EditText userName;

    private Context context;

    public UserSearchListener(EditText userName, Context context)
    {
        this.userName = userName;
        this.context = context;
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        AsyncRquest asyncTask = new AsyncRquest(URLConstant.SEARCH_USER, "user_name="+userName.getText().toString());

        AsyncTask<Object, Object, String> task = asyncTask.execute();

        try {
            String receive = task.get();

            JSONObject object = new JSONObject(receive);

            Gson son = new Gson();

            ReceiveListData user = son.fromJson(receive, ReceiveListData.class);

            if (0 == user.getStatus()) {
                Toast.makeText(context, user.getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }

            Class<?> classObj = context.getClass();

            List<User> userList = (List<User>) classObj.getMethod("getUserList").invoke(context);

            userList.clear();

            List<User> receiveList = user.getData();

            int length = receiveList.size();



            for (int index = 0; index < length; index++) {
                userList.add(receiveList.get(index));
            }
//            System.out.println(userList);
            classObj.getMethod("setUserList", List.class).invoke(context, userList);
            receiveList.clear();

        } catch (Exception e) {
           System.out.println(e.getMessage());
        }


    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
